/*
 * @Author: your name
 * @Date: 2021-05-29 16:43:21
 * @LastEditTime: 2021-06-06 14:14:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/pages/order/consumption/index.tsx
 */
/*
 * @Author: your name
 * @Date: 2021-05-22 21:52:40
 * @LastEditTime: 2021-05-29 16:39:42
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/pages/order/index.tsx
 */
import { IForm } from '@/components/form/interface';
import {
  Card,
  Modal,
  Popover,
  Radio,
  Row,
  Select,
  Table,
  TablePaginationConfig,
  Tabs,
  Tag,
} from 'antd';
import React from 'react';
import { IFormTypeEnum } from '@/components/form/formComponent';
import HeaderForm from '@/components/form';
import { useRequest } from '@/.umi/plugin-request/request';
import {
  change_order_status,
  get_admin_list,
  get_appointment_user,
  get_consume_list,
  get_order_detail,
  get_recharge_list,
  get_service_order,
  get_user_rights,
} from '@/services/pages';
import initPagination from '@/use/initPagination';
import useObj from '@/use/useObj';
import { useEffect } from 'react';
import room from '@/assets/img/room.png';
import { formatDateTime } from '@/utils/utils';
import {
  IS_Super,
  OrderStatus,
  PayType,
  ProjectStatus,
  ProjectStatusList,
  VipLevel,
} from '@/enum';
import { Space, message } from 'antd';
import { Button } from 'antd';
import _ from 'lodash';
import style from './index.less';
import { Col } from 'antd';
import useState from 'react';
import { MoneyCollectOutlined } from '@ant-design/icons';
interface IProps {}

const AllOrder = (props: IProps) => {
  const [obj, setObj] = useObj({
    ...initPagination,
    visible: false,
    refresh: null,
    row: null,
    query: {
      search: null,
      status: -1,
      start_time: null,
      end_time: null,
    },
    orderList: [],
    errorInfo: null,
  });

  const { data, error, loading } = useRequest(
    () =>
      get_service_order({
        page_size: obj.pagination.pageSize,
        page_num: obj.pagination.current,
        ...obj.query,
      }),
    {
      refreshDeps: [obj.pagination, obj.refresh, obj.query],
    },
  );
  const getVipList = useRequest(() => get_appointment_user({}));
  const getOrderDetail = useRequest(get_order_detail, { manual: true });

  useEffect(() => {
    setObj((obj) => {
      obj.pagination.total = data?.results[0]?.total || 0;
    });
  }, [data]);

  useEffect(() => {
    if (!obj.visible) {
      setObj({ errorInfo: null });
    }
  }, [obj.visible]);

  const columns: IForm[] = [
    {
      key: 'order_no',
      dataIndex: 'order_no',
      title: '订单单号',
    },
    {
      key: 'box_name',
      dataIndex: 'box_name',
      title: '包厢名称',
      width: 160,
    },
    {
      key: 'projects_total_price',
      dataIndex: 'projects_total_price',
      title: '项目总价(元)',
      render: (text) => {
        return <span>{text / 100}</span>;
      },
    },
    {
      key: 'total_price',
      dataIndex: 'total_price',
      title: '总价(元)',
      render: (text) => {
        return <span>{text / 100}</span>;
      },
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: '订单状态',
      render: (text) => {
        if (text === 0) {
          return (
            <Tag color="red">
              {OrderStatus[text as keyof typeof OrderStatus]}
            </Tag>
          );
        } else if (text === 1) {
          return (
            <Tag color="#87d068">
              {OrderStatus[text as keyof typeof OrderStatus]}
            </Tag>
          );
        } else {
          return (
            <Tag color="default">
              {OrderStatus[text as keyof typeof OrderStatus]}
            </Tag>
          );
        }
      },
    },

    {
      key: 'create_time',
      dataIndex: 'create_time',
      title: '创建时间',
      width: 200,
      render: (text) => {
        return formatDateTime(text);
      },
    },
    {
      key: 'content',
      dataIndex: 'content',
      title: '操作',
      render: (text, record) => {
        return (
          <Button
            onClick={(e) => {
              setObj({
                visible: true,
                orderList: JSON.parse(text),
                row: record,
              });
            }}
          >
            结账详情
          </Button>
        );
      },
    },
  ];

  const orderColumns = [
    {
      key: 'project_name',
      dataIndex: 'project_name',
      title: '项目名称',
      width: 100,
    },
    {
      key: 'staff_name',
      dataIndex: 'staff_name',
      title: '技师',
      width: 80,
    },
    {
      key: 'pay_true_price',
      dataIndex: 'pay_true_price',
      title: '项目价格(元)',
      width: 100,
      render: (text) => {
        return <span>{text / 100}</span>;
      },
    },
    {
      key: 'reserve_user_name',
      dataIndex: 'reserve_user_name',
      title: '预约人',
      width: 100,
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: '状态',
      width: 100,
      render: (text) => {
        return <span>{ProjectStatus[text as keyof typeof ProjectStatus]}</span>;
      },
    },
    // {
    //   key: 'reserve_vip_level',
    //   dataIndex: 'reserve_vip_level',
    //   title: '会员等级',
    //   width: 100,
    //   render: (text) => {
    //     return VipLevel[text as keyof typeof VipLevel];
    //   },
    // },
    {
      key: 'start_time',
      dataIndex: 'start_time',
      title: '开始时间',
      width: 120,
      render: (text) => {
        return formatDateTime(text);
      },
    },
    {
      key: 'end_time',
      dataIndex: 'end_time',
      title: '结束时间',
      width: 120,
      render: (text) => {
        return formatDateTime(text);
      },
    },
    {
      key: 'opt',
      dataIndex: 'opt',
      title: '付款人&支付方式',
      width: 350,
      render: (text, record, index) => {
        return (record.status == 1 || record.status == 2) && PayWay(record);
      },
    },
  ];

  const PayWay = (item: any) => {
    const getVipInfo = useRequest(get_user_rights, {
      manual: true,
    });

    return (
      <div key={item.schedule_id}>
        <Row>
          <Col span={6} className="gray-text" style={{ textAlign: 'right' }}>
            付款人：
          </Col>
          <Col span={18}>
            {obj.row?.status === 0 ? (
              <Select
                placeholder="付款人"
                style={{ width: '100%' }}
                // allowClear
                showSearch
                optionFilterProp="label"
                onChange={(e) => {
                  getVipInfo.run({ user_id: e });
                  console.log(obj.orderList, 'obj.orderList==');
                  console.log(item, 'obj.item==');

                  setObj((obj) => {
                    _.map(obj.orderList, (r) => {
                      if (r.schedule_id === item.schedule_id) {
                        r.user_id = e;
                      }
                    });
                  });
                }}
              >
                {_.map(getVipList.data?.results, (row, index) => {
                  return (
                    <Select.Option
                      key={row.user_id}
                      value={row.user_id}
                      label={row.user_name}
                    >
                      {row.user_name}
                    </Select.Option>
                  );
                })}
              </Select>
            ) : (
              item.pay_user_name
            )}
          </Col>
        </Row>
        <Row style={{ marginTop: 15 }}>
          <Col span={6} className="gray-text" style={{ textAlign: 'right' }}>
            支付方式：
          </Col>
          <Col span={18}>
            {obj.row?.status === 0 ? (
              <Radio.Group
                value={item.pay_type}
                onChange={(e) => {
                  console.log(item, 'iten===');
                  console.log(obj.orderList, 'obj.orderList===');

                  setObj((obj) => {
                    _.map(obj.orderList, (r) => {
                      if (r.schedule_id === item.schedule_id) {
                        r.pay_type = e.target.value;
                      }
                    });
                  });
                  console.log(e.target.value, 'e====');
                }}
              >
                <Radio value={1}>{PayType[1]}</Radio>
                <Radio
                  value={2}
                  disabled={
                    !getVipInfo.data?.results.storeRights ||
                    getVipInfo.data?.results.storeRights.length === 0
                  }
                >
                  {PayType[2]}
                </Radio>
                <Radio value={3}>{PayType[3]}</Radio>
              </Radio.Group>
            ) : (
              PayType[Number(item.pay_type) as keyof typeof PayType]
            )}
          </Col>
        </Row>
        {obj.row?.status === 0 && (
          <React.Fragment>
            <Row style={{ marginTop: 15 }}>
              <Col span={6} style={{ textAlign: 'right' }}>
                <span className="gray-text">账户余额：</span>
              </Col>
              <Col span={18}>
                {getVipInfo.data?.results.balance / 100 || 0}元
              </Col>
            </Row>
            <Row style={{ marginTop: 15 }}>
              <Col span={6} style={{ textAlign: 'right' }}>
                <span className="gray-text">账户权益：</span>
              </Col>
              <Col span={18}>
                {getVipInfo.data?.results.storeRights.length > 0
                  ? _.map(
                      getVipInfo.data?.results.storeRights,
                      (row, index) => {
                        return (
                          <div>
                            项目名称：{row.project_name}
                            <span style={{ marginLeft: 15 }}>
                              可用次数：{row.count}
                            </span>
                          </div>
                        );
                      },
                    )
                  : '无权益'}
              </Col>
            </Row>
          </React.Fragment>
        )}
      </div>
    );
  };
  const List: IForm[] = [
    {
      key: 'search',
      type: IFormTypeEnum.Input,
      label: '搜索',
      placeholder: '搜索',
      // placeholder: '订单状态, 包厢名称, 项目名称, 用户名称, 技师名称',
    },
    {
      key: 'status',
      type: IFormTypeEnum.Select,
      data: { list: ProjectStatusList },
      label: '状态',
    },
    {
      key: 'time',
      type: IFormTypeEnum.RangePicker,
      label: '创建时间',
    },
  ];

  const paymentOrder = async () => {
    const payList = _.filter(
      obj.orderList,
      (row) => row.status == 1 || row.status == 2,
    ).map((r) => {
      return {
        schedule_id: r.schedule_id,
        user_id: r.user_id,
        pay_type: r.pay_type,
      };
    });

    const data = {
      order_id: obj.row.order_id,
      pay_arr: payList,
      status: 1,
    };

    change_order_status(data)
      .then((res) => {
        message.success('支付成功');
        setObj({
          refresh: Symbol(),
          visible: false,
        });
      })
      .catch((e) => {
        if (e.code === -4) {
          setObj({ errorInfo: e.results.payMsg || e.message });
        } else if (e.code === -5) {
          setObj({ errorInfo: e.results.payMsg || e.message, refresh: true });
          getOrderDetail.run({ order_id: obj.row?.order_id }).then((res) => {
            console.log(res, 'res====');

            setObj({ row: res.results });
          });
        }
      });
  };

  return (
    <div className="allOrder">
      <HeaderForm
        list={List}
        style={{ marginBottom: 15 }}
        onSubmit={(form) => {
          setObj((obj) => {
            obj.query.search = form.search;
            obj.query.status = form.status;
            obj.query.start_time = form.time && form.time[0].unix();
            obj.query.end_time = form.time && form.time[1].unix();
          });
        }}
      />
      <Table
        rowKey={(record) => record.admin_id}
        loading={loading}
        columns={columns}
        dataSource={data?.results}
        pagination={obj.pagination}
        onChange={(pagination: TablePaginationConfig): void => {
          const { current, pageSize } = pagination;
          setObj((obj: any) => {
            obj.pagination.current = current;
            obj.pagination.pageSize = pageSize;
            obj.onReFresh = Symbol();
          });
        }}
      />
      {obj.visible && (
        <Modal
          width={'100%'}
          wrapClassName="order-detail-modal"
          visible={obj.visible}
          onCancel={() => {
            setObj({ visible: false });
          }}
          footer={null}
          title="订单详情"
          maskClosable={false}
          centered
        >
          <Table
            columns={orderColumns}
            dataSource={obj.orderList}
            pagination={false}
            rowKey={(record) => record.schedule_id}
          />
          <div style={{ textAlign: 'right', marginTop: '30px' }}>
            <div style={{ color: 'red' }}>{obj.errorInfo}</div>

            {obj.row?.status === 0 && (
              <Button
                icon={<MoneyCollectOutlined />}
                type="primary"
                style={{ width: 100 }}
                onClick={() => {
                  paymentOrder();
                }}
              >
                结账
              </Button>
            )}
          </div>
        </Modal>
      )}
    </div>
  );
};
export default AllOrder;
